package com.example.demofx;

import com.example.demofx.master.*;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.util.*;
import java.util.stream.Collectors;

public class MainApp extends Application implements ContactSavedListener, GroupChangedListener {
    private static final int ITEMS_PER_PAGE = 10;//分页器一页能展示的最大联系人数量
    private ObservableList<Contact> allData = FXCollections.observableArrayList();//存储所有联系人的数据
    private ContactManager contactManager;//联系人管理
    private GroupManager groupManager;//联系组管理
    private TableAndPaginationCreator tableAndPaginationCreator;//表格与分页器创建器
    private SidebarCreator sidebarCreator;//侧边栏创建器
    private TextField searchBox;//搜索输入框
    private Button searchButton;//搜索按钮
    private ContactFileManager fileManager; // 文件操作管理器


//返回一个选中状态为已选中的联系人列表
    private List<Contact> getSelectedContactFromTable() {
        List<Contact> selectedContacts = new ArrayList<>();
        ObservableList<Contact> allContacts = tableAndPaginationCreator.getAllData();
        for (Contact contact : allContacts) {
            if (contact.isSelected()) {
                selectedContacts.add(contact);
            }
        }
        return selectedContacts;
    }


    @Override
    public void start(Stage stage) {
        // 初始化 ContactManager 和 GroupManager
        contactManager = new ContactManager();
        groupManager = new GroupManager();
        // 初始化文件管理器
        fileManager = new ContactFileManager(
                contactManager,
                this,
                this,
                sidebarCreator,
                tableAndPaginationCreator
        );
        // 联系人更新监听器
        contactManager.addContactUpdateListener(updatedContact -> {
            System.out.println("收到联系人更新通知，开始刷新表格");
            if (tableAndPaginationCreator != null) {
                tableAndPaginationCreator.refreshTable();
            }
        });

        // 加载所有联系人到 ObservableList
        allData = FXCollections.observableArrayList(contactManager.getAllContacts());
        System.out.println("初始化时加载的联系人数量: " + allData.size());

        // 创建表格和分页器
        tableAndPaginationCreator = new TableAndPaginationCreator(allData, ITEMS_PER_PAGE, contactManager, this, groupManager);
//        tableAndPaginationCreator.updateAllData(); // 显式更新数据

        // 创建侧边栏
        sidebarCreator = new SidebarCreator(contactManager, groupManager, this);
        VBox sidebar = sidebarCreator.createSidebar(); // 先调用 createSidebar() 初始化 groupList

        // 获取分组列表并添加监听器
        ListView<String> groupList = sidebarCreator.getGroupList();
        if (groupList != null) { // 防止 null 引用
            groupList.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
                if (newVal != null) {
                    // 提取组名（去掉后面的“（数量）”）
                    String groupName = newVal.split(" \\(")[0];
                    // 根据组名查找对应的 Group 对象
                    Group selectedGroup = groupManager.getGroups().stream()
                            .filter(g -> g.getGroupName().equals(groupName))
                            .findFirst()
                            .orElse(null);

                    if (selectedGroup != null) {
                        // 过滤出属于该组的联系人
                        List<Contact> filteredContacts = contactManager.getAllContacts().stream()
                                .filter(contact -> contact.getGroups().contains(selectedGroup))
                                .collect(Collectors.toList());
                        // 更新表格数据
                        tableAndPaginationCreator.updateData(FXCollections.observableArrayList(filteredContacts));
                    } else {
                        // 显示所有联系人
                        tableAndPaginationCreator.updateData(allData);
                    }
                }
            });
        }

        // 监听 contactList 的选择变化
        ListView<String> contactList = sidebarCreator.getContactList();
        if (contactList != null) {
            contactList.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
                if (newVal != null) {
                    if (newVal.startsWith("所有联系人")) {
                        tableAndPaginationCreator.updateData(allData);
                    } else if (newVal.startsWith("未分组联系人")) {
                        List<Contact> ungrouped = contactManager.getAllContacts().stream()
                                .filter(c -> c.getGroups().isEmpty())
                                .collect(Collectors.toList());
                        tableAndPaginationCreator.updateData(FXCollections.observableArrayList(ungrouped));
                    }
                }
            });
        }
        HBox buttonBox1 = new HBox(5);
        HBox buttonBox2 = new HBox(5);
        HBox buttonBox3 = new HBox(5);
        HBox buttonBox4 = new HBox(5);
        HBox buttonBox5 = new HBox(5);

        // 创建内容区域的容器
        VBox contentContainer = new VBox(10);

        // 上方按钮
        Button newContactButton = new Button("新建联系人");
        Button deleteButton = new Button("删除");
        Button newGroupButton = new Button("新建组");
//        Button editGroupButton = new Button("编辑组");
        Button copyToGroupButton = new Button("复制到组");
        Button removeFromGroupButton = new Button("移除出组");
        Button moveToGroupButton = new Button("移动到组");
        Button deleteGroupButton = new Button("删除组");

        Button importButton = new Button("导入");
        Button exportButton = new Button("导出");

        // 创建按钮容器（导入/导出 按钮）
        HBox importExportButtons = new HBox(10, importButton, exportButton);

        // 将按钮容器添加到内容区域
        contentContainer.getChildren().add(importExportButtons);

//        Button searchButton = new Button("搜索");
//        TextField searchBox = new TextField();
//        searchBox.setPromptText("输入联系人的名字");
        searchBox = new TextField();
        searchBox.setPromptText("输入联系人的名字、电话、拼音等");

        searchButton = new Button("搜索");
        searchButton.setOnAction(e -> {
            String keyword = searchBox.getText().trim();
            System.out.println("用户输入搜索关键字: " + keyword);
            if (!keyword.isEmpty()) {
                List<Contact> searchResults = contactManager.searchContacts(keyword);
                System.out.println("ContactManager 返回的搜索结果数量: " + searchResults.size());
                if (searchResults.isEmpty()) {
                    // 查询结果为空，显示提示弹窗
                    showAlert("提示", "没有查到符合条件的联系人！请重新输入查询信息");
                    // 显示全部联系人信息
                    List<Contact> allContacts = contactManager.getAllContacts();
                    allData.setAll(allContacts);
                    tableAndPaginationCreator.updateData(FXCollections.observableArrayList(allContacts));
                } else {
                    allData.setAll(searchResults);
                    tableAndPaginationCreator.updateData(FXCollections.observableArrayList(searchResults));
                }
            } else {
                // 输入框为空，显示全部联系人信息
                List<Contact> allContacts = contactManager.getAllContacts();
                System.out.println("输入框为空，显示全部联系人信息，数量: " + allContacts.size());
                allData.setAll(allContacts);
                tableAndPaginationCreator.updateData(FXCollections.observableArrayList(allContacts));
            }
        });


        buttonBox1.getChildren().addAll(deleteButton);
        buttonBox2.getChildren().addAll(newGroupButton);
        buttonBox3.getChildren().addAll(copyToGroupButton);
        buttonBox4.getChildren().addAll(moveToGroupButton);
        buttonBox4.getChildren().addAll(removeFromGroupButton);
        buttonBox5.getChildren().addAll(deleteGroupButton);


        VBox centerLayout = tableAndPaginationCreator.createTableAndPagination();

        // 创建主布局
        BorderPane mainLayout = new BorderPane();
        mainLayout.setLeft(sidebar);

        // 顶部按钮布局
        HBox topButtonLayout = new HBox(10);
        topButtonLayout.getChildren().addAll(newContactButton, buttonBox1, buttonBox2, buttonBox3, buttonBox4, buttonBox5, searchBox, searchButton);
        topButtonLayout.setPadding(new Insets(10));
        mainLayout.setTop(topButtonLayout);


        contentContainer.setPadding(new Insets(10));

        // 将分页器添加到内容容器
        contentContainer.getChildren().add(centerLayout);

//        contentContainer.getChildren().add(importExportButtons);
        mainLayout.setCenter(contentContainer);

        // 新建联系人按钮事件处理
        newContactButton.setOnAction(e -> {
            ContactWindow contactWindow = new ContactWindow(contactManager);
            // 调用 setContactSavedListener 方法设置监听器
            contactWindow.setContactSavedListener(this);
            contactWindow.start(new Stage());
        });

        // 删除联系人按钮事件处理
        deleteButton.setOnAction(e -> {
            List<Contact> selectedContacts = getSelectedContactFromTable();
            if (!selectedContacts.isEmpty()) {
                // 显示确认对话框
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("确认删除");
                alert.setHeaderText(null);
                alert.setContentText("确定要删除选中的联系人吗？");

                if (alert.showAndWait().get() == ButtonType.OK) {
                    // 执行删除操作
                    for (Contact contact : selectedContacts) {
                        contactManager.deleteContact(contact.getId());
                    }
                    // 触发联系人保存事件以更新UI
                    onContactSaved();
                }
            } else {
                showAlert("提示", "请先勾选要删除的联系人");
            }
        });

        // 新建组按钮事件处理
        newGroupButton.setOnAction(e -> {
            GroupCreate contactGroupPopup = new GroupCreate(groupManager, contactManager); // 传递 contactManager

            contactGroupPopup.setGroupCreationListener(() -> {
                sidebarCreator.updateGroupList();
                sidebarCreator.updateContactList();
                onGroupChanged();

                // Show success dialog
                showAlert("成功", "组保存成功");
            });

            Stage popupStage = new Stage();
            contactGroupPopup.start(popupStage);
        });


        // 删除组按钮事件处理
        deleteGroupButton.setOnAction(e -> {
            String selectedGroupItem = sidebarCreator.getSelectedGroupName();
            if (selectedGroupItem != null && !selectedGroupItem.isEmpty()) {
                String groupName = selectedGroupItem.split(" \\(")[0];
                Group selectedGroup = groupManager.getGroups().stream()
                        .filter(g -> g.getGroupName().equals(groupName))
                        .findFirst()
                        .orElse(null);

                if (selectedGroup != null) {
                    // 创建自定义对话框
                    ChoiceDialog<String> dialog = new ChoiceDialog<>("只删除组", "只删除组", "删除组和其中的联系人");
                    dialog.setTitle("删除分组");
                    dialog.setHeaderText("确认删除分组：" + selectedGroup.getGroupName());
                    dialog.setContentText("请选择删除方式：");

                    Optional<String> result = dialog.showAndWait();
                    result.ifPresent(choice -> {
                        try {
                            if ("只删除组".equals(choice)) {
                                // 只删除组，保留联系人
                                groupManager.removeGroup(selectedGroup);
                                // 从所有联系人中移除该组关联
                                contactManager.getAllContacts().forEach(contact -> {
                                    contact.getGroups().remove(selectedGroup);
                                });
                            } else if ("删除组和其中的联系人".equals(choice)) {
                                // 删除组及其所有联系人
                                List<Contact> contactsInGroup = contactManager.getContactsByGroup(selectedGroup);
                                contactsInGroup.forEach(contact -> contactManager.deleteContact(contact.getId()));
                                groupManager.removeGroup(selectedGroup);
                            }

                            // 清除选中状态并更新UI
                            sidebarCreator.getGroupList().getSelectionModel().clearSelection();
                            onGroupChanged();
                            showAlert("成功", "分组删除成功！");
                        } catch (Exception ex) {
                            showAlert("错误", "删除分组时出错：" + ex.getMessage());
                        }
                    });
                } else {
                    showAlert("提示", "请先选中要删除的分组！");
                }
            } else {
                showAlert("提示", "请先选中要删除的分组！");
            }
        });

        // 移动到组按钮事件处理
        moveToGroupButton.setOnAction(e -> {
            List<Contact> selectedContacts = getSelectedContactFromTable();
            if (!selectedContacts.isEmpty()) {
                // 弹出选择组的窗口
                SelectGroupWindow selectGroupWindow = new SelectGroupWindow(groupManager);
                Optional<Group> selectedGroup = selectGroupWindow.showAndWait();

                if (selectedGroup.isPresent()) {
                    for (Contact contact : selectedContacts) {
                        // 需要先移除原有组关联
                        groupManager.removeContactFromAllGroups(contact);
                        groupManager.addContactToGroup(contact, selectedGroup.get());
                    }
                    // 更新分组列表
                    sidebarCreator.updateGroupList();
                    // 更新侧边栏联系人列表
                    sidebarCreator.updateContactList();
                    onGroupChanged(); // 触发组变更事件以更新UI
                }
            } else {
                showAlert("提示", "请先勾选要移动的联系人！");
            }
        });

        // 移除出组按钮事件处理
        removeFromGroupButton.setOnAction(e -> {
            List<Contact> selectedContacts = getSelectedContactFromTable();
            Group selectedGroup = getSelectedGroup();

            if (selectedContacts.isEmpty()) {
                showAlert("提示", "请先勾选要移出的联系人");
                return;
            }

            if (selectedGroup == null) {
                showAlert("提示", "请先在侧边栏选中一个组");
                return;
            }

            // 确认对话框
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("确认移出");
            alert.setHeaderText("确定要将 " + selectedContacts.size() + " 个联系人从组 \"" + selectedGroup.getGroupName() + "\" 中移出吗？");
            alert.setContentText("此操作不会删除联系人，仅移除组关联。");

            alert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    try {
                        // 从组中移除联系人
                        for (Contact contact : selectedContacts) {
                            if (groupManager.removeContactFromGroup(contact, selectedGroup)) {
                                // 从内存中移除联系人与组的关联
                                contact.getGroups().remove(selectedGroup);
                            }
                        }

                        // 更新组内联系人数量
                        groupManager.updateGroup(selectedGroup, contactManager);
                        sidebarCreator.updateGroupList(); // 更新侧边栏组列表（显示最新数量）
                        tableAndPaginationCreator.refreshTable(); // 刷新表格显示
                        // 刷新UI
                        onContactSaved();
                        showAlert("成功", "联系人已从组中移出");
                    } catch (Exception ex) {
                        showAlert("错误", "移出组时出错：" + ex.getMessage());
                    }
                }
            });
        });

        // 复制到组按钮事件处理
        copyToGroupButton.setOnAction(e -> {
            List<Contact> selectedContacts = getSelectedContactFromTable();
            if (!selectedContacts.isEmpty()) {
                // 弹出选择组的窗口
                SelectGroupWindow selectGroupWindow = new SelectGroupWindow(groupManager);
                Optional<Group> selectedGroup = selectGroupWindow.showAndWait();

                if (selectedGroup.isPresent()) {
                    for (Contact contact : selectedContacts) {
                        groupManager.addContactToGroup(contact, selectedGroup.get());
                    }
                    onGroupChanged(); // 触发组变更事件以更新UI
                }
            } else {
                showAlert("提示", "请先勾选要复制的联系人！");
            }
        });

        // 搜索框事件处理
        searchBox.textProperty().addListener((observable, oldValue, newValue) -> {
            filterContactsBySearch(newValue);
        });
        // 导入按钮事件处理
        importButton.setOnAction(e -> {
            fileManager.handleImportButtonClick(stage);
        });

        // 导出按钮事件处理
        exportButton.setOnAction(e -> {
            List<Contact> selectedContacts = getSelectedContactFromTable();
            fileManager.handleExportButtonClick(stage, selectedContacts);
        });


        // 获取表格视图并设置点击事件
        Pagination pagination = tableAndPaginationCreator.getPagination();
        TableView<Contact> tableView = (TableView<Contact>) ((ScrollPane) pagination.getPageFactory().call(0)).getContent();

        // 添加“所在组”列
        TableColumn<Contact, String> groupColumn = new TableColumn<>("所在组");
        groupColumn.setCellValueFactory(cellData -> {
            Contact contact = cellData.getValue();
            System.out.println("联系人姓名" + contact.getName());
            return Bindings.createStringBinding(() -> {
                System.out.println("联系人组" + contact.getGroups());
                if (contact.getGroups() != null && !contact.getGroups().isEmpty()) {
                    StringBuilder groupsStr = new StringBuilder();
                    for (Group group : contact.getGroups()) {
                        if (groupsStr.length() > 0) {
                            groupsStr.append(", ");
                        }
                        groupsStr.append(group.getGroupName());
                    }
                    return groupsStr.toString();
                } else {
                    return "";
                }
            }, contact.getGroups());
        });
        tableView.getColumns().add(groupColumn);

        TableColumn<Contact, String> nameColumn = new TableColumn<>("姓名");
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameColumn.setOnEditCommit(event -> {
            Contact selectedContact = event.getRowValue();
//            openContactWindow(selectedContact);
        });



        Scene scene = new Scene(mainLayout, 1200, 800);
        stage.setTitle("通讯录应用程序");
        stage.setScene(scene);
        stage.show();
    }
    // 错误提示
    private void showAlert(String title, String content) {
        javafx.scene.control.Alert alert = new javafx.scene.control.Alert(javafx.scene.control.Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    // 根据搜索框内容过滤联系人
    private void filterContactsBySearch(String keyword) {
        List<Contact> filteredContacts = contactManager.findContactsByName(keyword);
        allData.setAll(filteredContacts);
    }


    private Group getSelectedGroup() {
        // 从分组列表获取选中的项
        ListView<String> groupList = sidebarCreator.getGroupList();
        String selectedItem = groupList.getSelectionModel().getSelectedItem();

        if (selectedItem == null) {
            return null;
        }

        // 提取组名（去掉后面的“（数量）”）
        String groupName = selectedItem.split(" \\(")[0];

        // 查找对应的 Group 对象
        return groupManager.getGroups().stream()
                .filter(g -> g.getGroupName().equals(groupName))
                .findFirst()
                .orElse(null);
    }


    @Override
    public void onContactSaved() {
        System.out.println("\n=== 开始处理联系人保存事件 ===");
        System.out.println("进入 onContactSaved 方法，开始重新加载数据");
        
        if (tableAndPaginationCreator != null) {
            // 重新加载所有数据
            System.out.println("正在从 ContactManager 获取更新后的联系人列表");
            ObservableList<Contact> updatedContacts = contactManager.getAllContacts();
            System.out.println("获取到更新后的联系人列表，数量: " + updatedContacts.size());
            
            // 更新表格数据
            System.out.println("开始更新表格数据");
            tableAndPaginationCreator.updateData(updatedContacts);
            System.out.println("表格数据已更新");
            
            // 更新侧边栏联系人数量统计
            if (sidebarCreator != null) {
                System.out.println("开始更新侧边栏");
                sidebarCreator.updateGroupList();
                sidebarCreator.updateContactList();
                System.out.println("侧边栏已更新");
            } else {
                System.out.println("警告：sidebarCreator 为 null，无法更新侧边栏");
            }
            
            System.out.println("数据更新完成，联系人数量: " + updatedContacts.size());
        } else {
            System.err.println("错误：tableAndPaginationCreator 为 null，无法更新数据");
        }
        System.out.println("=== 联系人保存事件处理完成 ===\n");
    }



    @Override
    public void onGroupChanged() {
        if (sidebarCreator != null) {
            sidebarCreator.updateGroupList();
            sidebarCreator.updateContactList();
        }

        if (tableAndPaginationCreator != null) {
            List<Contact> updatedContacts = contactManager.getAllContacts();
            tableAndPaginationCreator.updateData(FXCollections.observableArrayList(updatedContacts));
        }
    }



    public static void main(String[] args) {
        launch(args);
    }
}